<template>
	<view class="masonry-container">
		<!-- 瀑布流两列布局 -->
		<view class="masonry-column" v-for="(column, index) in 2" :key="index">
			<view class="masonry-item" v-for="(colItem, itemIndex) in filteredItems[index]" :key="colItem.item.id"
				@click="handleItemClick(colItem.item)">
				<view class="eys displayFlexSpaceBetween">
					<view class="eys-left displayFlex">
						<image src="/static/images/my/eys.svg"></image>
						<text>{{colItem.item.LiulanL}}</text>
					</view>
					<!-- <view class="eys-right" v-show="item.ShipinTPLXC === '视频'?true:false">
						<image src="/static/images/my/icon-视频@2x.png"></image>
					</view> -->
				</view>
				<!-- 图片类型 -->
				<view class="media-container image-container" v-if="TupianMSList[colItem.globalIndex]">
					<image :src="TupianMSList[colItem.globalIndex]" mode="widthFix" class="media-item" lazy-load
						@load="handleMediaLoad(colItem.item, index, itemIndex)"></image>
				</view>
				<!-- 视频类型 -->
				<!-- <view v-else="item.Shipin" class="media-container video-container">
					<video :src="item.Shipin" class="media-item" controls lazy-load
						@loadedmetadata="handleMediaLoad(item, index, itemIndex)"></video>
				</view> -->

				<!-- 内容信息 -->
				<view class="item-info">
					<view class="item-title">{{ colItem.item.Biaoti }}</view>
					<view class="item-meta displayFlexSpaceBetween">
						<view class="item-meta-box displayFlex">
							<image :src="Microi.FileServer + colItem.item.Avatar" mode="aspectFill"></image>
							<view class="biji-name">{{colItem.item.UserName }}</view>
							<text>{{ computeHDYear(colItem.item.CreateTime) }}</text>

						</view>
						<view class="item-meta-aixin displayFlex" @tap.stop="DianzanSC(colItem.item, index, '点赞')">
							<image v-if="colItem.item.myZan" src="/static/images/company/hongxin.png" mode="widthFix"></image>
							<image v-else src="/static/images/company/xin.png" mode="widthFix"></image>
							<text
								:style="{ color: colItem.item.myZan ? '#EA3325' : '#666666' }">{{ computeNum(colItem.item.ZanCount * 1) }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'MasonryMedia',
		// components: {
		//   // 引入uni-app的加载组件
		//   'uni-loading-icon': () => import('@/components/uni-loading-icon/uni-loading-icon.vue')
		// },
		props: {
			// 初始数据
			initialData: {
				type: Array,
				default: () => []
			},
			// 列数，默认为2
			columnCount: {
				type: Number,
				default: 2
			}
		},
		// watch: {
		//   initialData: {
		//     immediate: true,
		//     handler(newVal) {
		//       this.items = [...newVal];
		//       this.TupianMSList = newVal.map(item => {
		//         // 原 TupianMSList 解析逻辑...
		//       });
		//       this.distributeItems(newVal);
		//     }
		//   }
		// },
		data() {
			return {
				CurrentUser: this.Microi.GetCurrentUser(),
				Islogin: this.Microi.IsLogin(),
				// 所有项目
				items: [],
				// 每列的高度
				columnHeights: [0, 0],
				// 每列的项目
				filteredItems: [
					[],
					[]
				],
				// 加载状态
				loading: false,
				// 是否还有更多数据
				hasMore: true,
				// 当前页
				page: 1,
				// 每页数量
				pageSize: 10,
				TupianMSList: []
			};
		},
		// masonryDZ.vue 中启用 watch
		watch: {
		  initialData: {
		    immediate: true, // 初始化时执行一次
		    deep: true, // 深度监听数组/对象变化
		    handler(newVal) {
		      this.items = [...newVal];
		      // 重新解析图片路径
		      this.TupianMSList = newVal.map(item => {
		        if (item.TupianMS) {
		          try {
		            const tupianMSArr = JSON.parse(item.TupianMS);
		            return tupianMSArr.length > 0 ? this.Microi.FileServer + tupianMSArr[0].Path : '';
		          } catch (e) {
		            return '';
		          }
		        }
		        return '';
		      });
		      // 重新分配项目到列，更新布局
		      this.columnHeights = [0, 0]; // 重置列高度
		      this.filteredItems = [[], []]; // 清空列数据
		      this.distributeItems(newVal);
		    }
		  }
		},
		mounted() {
		  this.items = [...this.initialData];
		  console.log('this.items；', this.items);
		  // 初始化数组长度，与 items 对应
		  this.TupianMSList = new Array(this.items.length).fill(''); 
		  
		  this.items.forEach((item, index) => {
		    if (item.TupianMS) {
		      try {
		        let tupianMSArr = JSON.parse(item.TupianMS);
		        if (tupianMSArr && tupianMSArr.length > 0) {
		          // 为每个 item 存储对应的图片路径
		          this.TupianMSList[index] = this.Microi.FileServer + tupianMSArr[0].Path; 
		          console.log(`解析后的 TupianMS Path[${index}]:`, this.TupianMSList[index]);
		        }
		      } catch (e) {
		        console.error(`解析第 ${index} 个 TupianMS 失败:`, e);
		      }
		    }
		  });
		
		  this.distributeItems(this.initialData);
		},
		onShow() {

		},
		methods: {
			async DianzanSC(item, index, Caozuo = '点赞') {
				var self = this;

				// var res = await self.Microi.ApiEngine.Run('user_dianzanOrsc', {
				// 	Id: item.WenzhangID,
				// 	Caozuo: Caozuo,
				// 	Leixing: item.Leixing,
				// 	Type: item.myZan,
				// 	ZuozheID: item.ZuozheID
				// });
				console.log("点赞:", item, index);

			},
			computeNum(num) {
				num = num * 1;
				if (num > 10000) {
					return num / 10000 + 'w+';
				} else if (num > 1000) {
					return num / 1000 + 'k+';
				} else {
					return num;
				}
			},
			computeHDYear(DataInfo) {
				var time = new Date(DataInfo);
				var year = time.getFullYear();
				var month = time.getMonth() + 1;
				if (month < 10) month = `0${month}`;
				var day = time.getDate();
				if (day < 10) day = `0${day}`;
				var xingqi = time.getDay();
				var XingqiArray = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				xingqi = XingqiArray[xingqi];

				return `${year == new Date().getFullYear() ? '' : year} ${year}-${month}-${day} `;
			},
			/**
			 * 分配项目到不同列，保持列高度平衡
			 */
			// 修改 distributeItems
			distributeItems(newItems) {
			  newItems.forEach((item, globalIndex) => {
			    const minHeightColumn = this.columnHeights.indexOf(Math.min(...this.columnHeights));
			    this.filteredItems[minHeightColumn].push({ item, globalIndex }); 
			
			    const width = item.width || 300;
			    const height = item.height || 300;
			    const aspectRatio = width / height;
			    const estimatedHeight = 300 / aspectRatio;
			    this.columnHeights[minHeightColumn] += estimatedHeight + 80;
			  });
			},

			/**
			 * 媒体加载完成后更新高度
			 */
			handleMediaLoad(item, columnIndex, itemIndex) {
				// 获取实际宽高
				uni.createSelectorQuery()
					.in(this)
					.select(
						`.masonry-column:nth-child(${columnIndex + 1}) .masonry-item:nth-child(${itemIndex + 1}) .media-item`
					)
					.boundingClientRect(data => {
						if (data) {
							// 计算之前的预估高度
							const aspectRatio = item.width / item.height;
							const estimatedHeight = 300 / aspectRatio;

							// 计算差值并更新列高度
							const diff = data.height - estimatedHeight;
							this.columnHeights[columnIndex] += diff;
						}
					})
					.exec();
			},

			/**
			 * 处理项目点击
			 */
			handleItemClick(item) {
				this.$emit('item-click', item);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.masonry-container {
		display: flex;
		padding: 10rpx;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.masonry-column {
		width: calc(50% - 10rpx);
		/* 两列间距20rpx，每列占比50%减10rpx */
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.masonry-item {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.3s ease;
	}

	.masonry-item:hover {
		// transform: translateY(-4rpx);
	}

	.eys {
		position: absolute;
		z-index: 1;
		width: 50%;
		padding: 20rpx;

		// padding-top: -30rpx;
		// background-color: #777;
		&-left {
			image {
				width: 36rpx;
				height: 36rpx;
				margin-right: 10rpx;
			}

			text {
				font-weight: 400;
				font-size: 26rpx;
				color: #FFFFFF;
			}
		}

		&-right {
			image {
				width: 46rpx;
				height: 46rpx;
				margin-right: 60rpx;
			}
		}

	}

	.media-container {
		width: 100%;
		position: relative;
	}

	.media-item {
		width: 100%;
		display: block;
	}

	.item-info {
		padding: 16rpx;
	}

	.item-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.item-meta {
		display: flex;
		justify-content: space-between;
		font-weight: 500;
		font-size: 20rpx;

		&-box {
			image {
				width: 28rpx;
				height: 28rpx;
				border-radius: 50%;
			}

			view {
				color: #666666;
				margin: 0 15rpx;
			}

			text {
				color: #999999;
			}
		}

		&-aixin {
			image {
				width: 33rpx;
				height: 33rpx;
				margin-right: 10rpx;
			}

			text {
				font-weight: 400;
				font-size: 26rpx;

			}
		}
	}

	.load-more {
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.loading {
		display: flex;
		align-items: center;
		gap: 10rpx;
		color: #777;
		font-size: 26rpx;
	}

	.load-more-btn {
		background-color: #f5f5f5;
		color: #666;
		border: none;
		padding: 15rpx 40rpx;
		border-radius: 30rpx;
		font-size: 26rpx;
	}

	/* 解决视频初始加载时的样式问题 */
	video {
		object-fit: cover;
	}
</style>